import json
import sys
import os
from PIL import Image
import random


def random_image_description():
    descriptions = [
        "Describe the visual content of this image in detail.",
        "Provide a thorough explanation of what is depicted in the picture.",
        "Detail all visible elements and their arrangement in the image.",
        "Explain everything you observe in this photograph comprehensively.",
        "Give a complete breakdown of the visual elements present in this image.",
        "Break down every visible component and their context in this photograph.",
        "Characterize the entire visual scene represented in this image."
    ]
    return random.choice(descriptions)


def is_valid_image(img):
    width, height = img.size
    # must bigger than 28 pixels
    if width > 14 and height > 14:
        return True
    else:
        return False


def update_json_file(file_path):
    img_root = os.path.dirname(file_path)

    with open(file_path, "r", encoding="utf-8") as f:
        data = json.load(f)

    new_items = []
    for item in data:
        # if "images" not in item["image"]:
        # item["image"] = "images/" + item["image"]
        # image_path = os.path.join(img_root, item["image"])

        # check if image valid
        # try:
        #     img = Image.open(image_path)
        #     if is_valid_image(img):
        #         new_items.append(item)
        # except Exception as e:
        #     print(f"{image_path} {e}")
        item["conversations"][0]["value"] = (
            # "<image>\n" + item["conversations"][0]["value"]
            "<image>\n" + random_image_description()
        )
        # if item["conversations"][0]["value"].count('<video>') != 1:
        #     print(f'item error {item}')
        # else:
        #     new_items.append(item)
        
        new_items.append(item)

    file_path_new = file_path.replace(".json", "_fix.json")
    with open(file_path_new, "w") as f:
        json.dump(new_items, f, ensure_ascii=False, indent=2)
    print(f"done for: {len(data)} {len(new_items)}")


# Usage example
json_file_path = sys.argv[1]

update_json_file(json_file_path)
